package MTT::Controller::Search;
use Moose;
use namespace::autoclean;

BEGIN {extends 'Catalyst::Controller'; }

=head1 NAME

MTT::Controller::Search - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut


=head2 index

=cut

use utf8;

use Data::Dumper;
use POSIX qw(strftime);
use Class::Date qw(date);
use IO::File;
use HTML::Table;
use Log::Log4perl;

use MTT::Libs::Search;

sub index :Path :Args(0) {
    my ( $self, $c ) = @_;

	$c->stash->{template} = 'search.tt2';

	my (@trunks, %trs, @operators, %ops, %sws, @switches, @all, %all);

	my %table_names;
	foreach ( $c->model('DBIC::Switch')->search({status => 1}) ) {
		$sws{ $_->host_code } = $_->id_type->type . ' ' . $_->host_code;
		$table_names{ $_->id_type->table_name } = 1;
	}
	@switches = map { [ $_ => $sws{$_} ] } sort { $sws{$a} cmp $sws{$b} } keys %sws;
	my @host_codes = map { $_ } keys %sws;
	$c->stash->{table_names} = [ keys %table_names ];

	my $rs = $c->model('DBIC::Trunk')->search({
			created => { '>=' => \'DATE(now())' }, 
			switch => {in => \@host_codes}
		});
	$rs->result_class('DBIx::Class::ResultClass::HashRefInflator');

	foreach ( $rs->all() ) {
		$trs{ $_->{trunk} } = $_->{trunk};
		$ops{ $_->{company_name} } = $_->{company_name};
		push @all, [ $_->{switch}, $_->{trunk}, $_->{company_name} ];
	}

	no warnings;
	@trunks = map { [ $_ => $_ ] } 
		sort { 
			my $ad = $a =~ /^\d+$/;
			my $bd = $b =~ /^\d+$/;
			my ($aip) = $a =~ /^(\d+)\./;
			my ($bip) = $b =~ /^(\d+)\./;

			$ad && !$bd ? -1 :
			$bd && !$ad ?  1 :
			$ad && $bd ? $a <=> $b :
			$aip && !$bip ? -1 :
			$bip && !$aip ?  1 :
			$aip && $bip ? $aip <=> $bip :
			$a cmp $b
		} keys %trs;

	@operators = map { [ $_ => $_ ] } sort keys %ops;

	$c->stash->{sql} = [];

	if ( $c->req->method eq 'POST' ) {

		my $ci = $c->config->{CallDB}->{connect_info};
		my $dbh = DBI->connect(
			$ci->{dsn},
			$ci->{user},
			$ci->{password}
		) || die DBI->errstr;
		$dbh->do( $ci->{on_connect_do} );
		$dbh->{mysql_enable_utf8} = 1;

		my $s = MTT::Libs::Search->new(dbh => $dbh);
		my $format = $c->req->params->{format};
		$s->format( $format );

		$s->search($c);

		if ( $s->success() ) {
			if ( $format eq 'html' ) {
				
				$c->stash->{result} = $s->get_html();
				$c->stash->{result_header} = 'Всего найдено' . $s->result_rows() . ' записей';
			}
			elsif ( $format eq 'csv' ) {
				my $fh = IO::File->new( $s->file(), 'r' ) || die $!;
				$fh->binmode();

				my $file_num = $c->session->{csv_num} || 0;
				$file_num++;

				$c->response->content_type("text/csv; name=search_${file_num}.csv");
				$c->res->header(
					'Content-Disposition' => "attachment; filename=search_${file_num}.csv"
				);
				$c->session->{csv_num} = $file_num;

				$c->response->body( $fh );
				return;
			}
			elsif ( $format eq 'excel' ) {
				my $fh = IO::File->new( $s->file(), 'r' ) || die $!;
				$fh->binmode();

				my $file_num = $c->session->{excel_num} || 0;
				$file_num++;

				$c->response->content_type("application/excel; name=search_${file_num}.xls");
				$c->res->header(
					'Content-Disposition' => "attachment; filename=search_${file_num}.xls");
				$c->session->{excel_num} = $file_num;
				$c->response->body( $fh );
				return;
			}
		}
		else { 
			$c->stash->{result} = 'Ничего не найдено';
		}
	}

	unless ( $c->req->params->{start_time} ) {
		$c->req->params->{start_time} = strftime('%Y-%m-%d 00:00:00', localtime);
	}
	unless ( $c->req->params->{end_time} ) {
		$c->req->params->{end_time} = strftime('%Y-%m-%d 23:59:59', localtime);
	}

	$c->stash(
		switches => \@switches,
		trunks => \@trunks,
		operators => \@operators,
#		all => \@all,
#		sql => '<pre>' . join("\n", @{ $c->stash->{sql} } ) . '</pre>' 
	);
}


=head1 AUTHOR

Andrey Asyakin,,,,

=head1 LICENSE

This library is free software. You can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

__PACKAGE__->meta->make_immutable;

1;
